<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Nibbles in Java SWT</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="GUI, SWT, Nibbles, Java, Linux, programming, game">
<meta nam="description" content="In this part of the Java SWT tutorial, we create
a Nibbles game clone.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container2">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content2">


<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Nibbles</h1>

<p>
In this part of the Java SWT tutorial, we will create a Nibbles game clone.
</p>

<div class="big_hor">
<script type="text/javascript"><!--
google_ad_client = "ca-pub-9706709751191532";
/* big_horizontal */
google_ad_slot = "2904953388";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<p>
<b>Nibbles</b> is an older classic video game. It was first created in late 70s.
Later it was brought to PCs. In this game the player controls a snake.
The objective is to eat as many apples as possible. Each time the snake eats an apple,
its body grows. The snake must avoid the walls and its own body. 
</p>


<h2>Development</h2>

<p>
The size of each of the joints of a snake is 10px. The snake is controlled with 
the cursor keys. Initially, the snake has three joints. The game starts immediately. 
When the game is finished, we display "Game Over" message in the center of the window.
</p>

<pre class="code">
package com.zetcode;


import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;


public class Board extends Canvas {

    private final int WIDTH = 300;
    private final int HEIGHT = 300;
    private final int DOT_SIZE = 10;
    private final int ALL_DOTS = 900;
    private final int RAND_POS = 29;
    private final int DELAY = 140;

    private int x[] = new int[ALL_DOTS];
    private int y[] = new int[ALL_DOTS];

    private int dots;
    private int apple_x;
    private int apple_y;

    private boolean left = false;
    private boolean right = true;
    private boolean up = false;
    private boolean down = false;
    private boolean inGame = true;


    private Image ball;
    private Image apple;
    private Image head;

    private Display display;
    private Shell shell;
    private Runnable runnable;



    public Board(Shell shell) {

        super(shell, SWT.NULL);

        this.shell = shell;
        display = shell.getDisplay();

        setSize(WIDTH, HEIGHT);

        this.addPaintListener(new BoardPaintListener());
        this.addKeyListener(new BoardKeyListener());

        Color col = new Color(shell.getDisplay(), 0, 0, 0);

        this.setBackground(col);
        col.dispose();

        ImageData iib = new ImageData("dot.png");
        ball = new Image(display, iib);

        ImageData iia = new ImageData("apple.png");
        apple = new Image(display, iia);
        
        ImageData iih = new ImageData("head.png");
        head = new Image(display, iih);

        initGame(shell.getDisplay());
    }


    public void initGame(final Display display) {

        dots = 3;

        for (int z = 0; z &lt; dots; z++) {
            x[z] = 50 - z*10;
            y[z] = 50;
        }

        locateApple();

        runnable = new Runnable() {
          public void run() {
             if (inGame) {
                checkApple();
                checkCollision();
                move();

            }
            display.timerExec(DELAY, this);
            redraw();
          }
        };

        display.timerExec(DELAY, runnable);
    };


    private class BoardPaintListener implements PaintListener {

        public void paintControl(PaintEvent e) {

            Color col = new Color(shell.getDisplay(), 0, 0, 0);
            e.gc.setBackground(col);
            col.dispose();

            e.gc.setAntialias(SWT.ON);

            if (inGame) {
                drawObjects(e);
            } else {
                gameOver(e);
            }

            e.gc.dispose();

        }
    }


    public void drawObjects(PaintEvent e) {
        e.gc.drawImage(apple, apple_x, apple_y);

        for (int z = 0; z &lt; dots; z++) {
            if (z == 0) {
                e.gc.drawImage(head, x[z], y[z]);
            } else {
                e.gc.drawImage(ball, x[z], y[z]);
            }
        }
    }

    public void gameOver(PaintEvent e) {
        String msg = "Game Over";

        Font font = new Font(e.display, "Helvetica",
                12, SWT.NORMAL);
        Color white = new Color(shell.getDisplay(),
                255, 255, 255);

        Point size = e.gc.textExtent (msg);
                
        e.gc.setForeground(white);
        e.gc.setFont(font);
        e.gc.drawText(msg, (WIDTH - size.x) / 2, (HEIGHT - size.y) / 2);

        font.dispose();
        white.dispose();
        e.gc.dispose();
        display.timerExec(-1, runnable);

    }


    public void checkApple() {

        if ((x[0] == apple_x) &amp;&amp; (y[0] == apple_y)) {
            dots++;
            locateApple();
        }
    }


    public void move() {

        for (int z = dots; z > 0; z--) {
            x[z] = x[(z - 1)];
            y[z] = y[(z - 1)];
        }

        if (left) {
            x[0] -= DOT_SIZE;
        }

        if (right) {
            x[0] += DOT_SIZE;
        }

        if (up) {
            y[0] -= DOT_SIZE;
        }

        if (down) {
            y[0] += DOT_SIZE;
        }
    }


    public void checkCollision() {

        for (int z = dots; z > 0; z--) {

            if ((z &gt; 4) &amp;&amp; (x[0] == x[z]) &amp;&amp; (y[0] == y[z])) {
                inGame = false;
            }
        }

        if (y[0] &gt; HEIGHT - DOT_SIZE) {
            inGame = false;
        }

        if (y[0] &lt; 0) {
            inGame = false;
        }

        if (x[0] &gt; WIDTH - DOT_SIZE) {
            inGame = false;
        }

        if (x[0] &lt; 0) {
            inGame = false;
        }
    }

    public void locateApple() {
        int r = (int) (Math.random() * RAND_POS);
        apple_x = ((r * DOT_SIZE));
        r = (int) (Math.random() * RAND_POS);
        apple_y = ((r * DOT_SIZE));
    }

    private class BoardKeyListener extends KeyAdapter {

        @Override
        public void keyPressed(org.eclipse.swt.events.KeyEvent e) {

            int key = e.keyCode;

            if ((key == SWT.ARROW_LEFT) &amp;&amp; (!right)) {
                left = true;
                up = false;
                down = false;
            }

            if ((key == SWT.ARROW_RIGHT) &amp;&amp; (!left)) {
                right = true;
                up = false;
                down = false;
            }

            if ((key == SWT.ARROW_UP) &amp;&amp; (!down)) {
                up = true;
                right = false;
                left = false;
            }

            if ((key == SWT.ARROW_DOWN) &amp;&amp; (!up)) {
                down = true;
                right = false;
                left = false;
            }
        }
    }
}
</pre>

<p>
First we will define some globals used in our game. 
</p>

<p>
The WIDTH and HEIGHT constants determine the size of the Board. 
The DOT_SIZE is the size of the apple and the dot of the snake. The ALL_DOTS 
constant defines the maximum number of possible dots on the Board.
The RAND_POS constant is used to calculate a random position of an apple. 
The DELAY constant determines the speed of the game.
</p>

<pre class="explanation">
private int x[] = new int[ALL_DOTS];
private int y[] = new int[ALL_DOTS];
</pre>

<p>
These two arrays store x, y coordinates of all possible joints of a snake. 
</p>

<p>
The initGame() method initializes variables, loads images and starts a timeout function.
</p>

<pre class="explanation">
runnable = new Runnable() {
  public void run() {
      if (inGame) {
        checkApple();
        checkCollision();
        move();
    }
    display.timerExec(DELAY, this);
    redraw();
  }
};
</pre>

<p>
Every DELAY ms, the run() method is called. If we are in the game, we call 
three methods, that build the logic of the game.
</p>

<pre class="explanation">
if (inGame) {
    drawObjects(e);
} else {
    gameOver(e);
}
</pre>

<p>
Inside the <code>paintControl()</code> method, we check 
the inGame variable. If it is true, we draw our objects. 
The apple and the snake joints. Otherwise we display "Game over" text.  
</p>

<pre class="explanation">
public void drawObjects(PaintEvent e) {
    e.gc.drawImage(apple, apple_x, apple_y);

    for (int z = 0; z < dots; z++) {
        if (z == 0) {
            e.gc.drawImage(head, x[z], y[z]);
        } else {
            e.gc.drawImage(ball, x[z], y[z]);
        }
    }
}
</pre>

<p>
The drawObjects() method draws the apple and the joints of the
snake. The first joint of a snake is its head, which is represented by a red circle. 
</p>

<pre class="explanation">
public void checkApple() {

    if ((x[0] == apple_x) &amp;&amp; (y[0] == apple_y)) {
        dots++;
        locateApple();
    }
}
</pre>

<p>
The checkApple() method checks, if the snake has hit
the apple object. If so, we add another snake joint and call the 
locateApple() method, which randomly places a new apple object. 
</p>

<p>
In the move() method we have the key algorithm of the game. 
To understand it, look at how the snake is moving. You control the head of the snake. 
You can change its direction with the cursor keys. The rest of the joints move
one position up the chain. The second joint moves where the first was, 
the third joint where the second was etc. 
</p>

<pre class="explanation">
for (int z = dots; z > 0; z--) {
    x[z] = x[(z - 1)];
    y[z] = y[(z - 1)];
}
</pre>

<p>
This code moves the joints up the chain. 
</p>

<pre class="explanation">
if (left) {
    x[0] -= DOT_SIZE;
}
</pre>

<p>
Move the head to the left.
</p>

<p>
In the checkCollision() method, we determine if the snake has hit itself 
or one of the walls. 
</p>

<pre class="explanation">
for (int z = dots; z > 0; z--) {

    if ((z > 4) &amp;&amp; (x[0] == x[z]) &amp;&amp; (y[0] == y[z])) {
    inGame = false;
    }
}
</pre>

<p>
Finish the game, if the snake hits one of its joints with the head.
</p>

<pre class="explanation">
if (y[0] > HEIGHT - DOT_SIZE) {
    inGame = false;
}
</pre>

<p>
Finish the game, if the snake hits the bottom of the Board. 
</p>

<p>
The locateApple() method locates an apple randomly on the board.
</p>

<pre class="explanation">
int r = (int) (Math.random() * RAND_POS);
</pre>

<p>
We get a random number from 0 to RAND_POS - 1. 
</p>

<pre class="explanation">
apple_x = ((r * DOT_SIZE));
...
apple_y = ((r * DOT_SIZE));
</pre>

<p>
These line set the x, y coordinates of the apple
object. 
</p>

<p>
In the <code>keyPressed()</code> method of the BoardKeyListener class, we 
determine the keys that were pressed.
</p>

<pre class="explanation">
if ((key == SWT.ARROW_LEFT) &amp;&amp; (!right)) {
    left = true;
    up = false;
    down = false;
}
</pre>

<p>
If we hit the left cursor key, we set left variable to 
true. This variable is used in the move() method to change coordinates of the 
snake object. Notice also, that when the snake is heading to the right, we cannot 
turn immediately to the left. 
</p>

<pre class="code">
package com.zetcode;

import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

/**
 * ZetCode Java SWT tutorial
 *
 * In this code example, we create
 * a Nibbles game clone
 *
 * @author jan bodnar
 * website zetcode.com
 * last modified June 2009
 */


public class SWTApp {

    private Shell shell;

    public SWTApp(Display display) {

        shell = new Shell(display);

        shell.setText("Nibbles");

        initUI();

        shell.setSize(305, 330);
        shell.setLocation(300, 300);
        shell.open();

        while (!shell.isDisposed()) {
          if (!display.readAndDispatch()) {
            display.sleep();
          }
        }
    }


    public void initUI() {

        FillLayout layout = new FillLayout();
        shell.setLayout(layout);

        new Board(shell);
    }


    public static void main(String[] args) {
        Display display = new Display();
        new SWTApp(display);
        display.dispose();
    }
}
</pre>

<p>
In this class, we set up the Nibbles game. 
</p>

<pre class="explanation">
shell.setSize(305, 330);
</pre>

<p>
In SWT library, there is no platform independent way of calculating 
the size of the decorations of the window. Borders and title bar. Or 
I didn't find it. These two numbers fit my case. You may need to update
the width and height of the window to fit your case. 
</p>

<img src="/img/gui/swt/nibbles.png" alt="Nibbles">
<div class="figure">Figure: Nibbles</div>

<p>
This was the Nibbles computer game programmed with the SWT library 
and the Java programming language.
</p>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified June 15, 2009  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

